package com.dinghui.ebookbag.utils;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import androidx.core.content.FileProvider;

import com.dinghui.ebookbag.BuildConfig;
import com.dinghui.ebookbag.enity.VersionManager;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Jmh
 * on 2021-03-01
 * 版本更新   https://blog.csdn.net/weixin_44547558/article/details/86651889
 */
public class UpdateVersionHelper {
    private String downLoadPath = "";
    private String downloadUrl = "";//apk下载地址
    private boolean isforce = false;
    private String oldApkName = "";
    private String newApkName = "";
    private Context context;
    private ProgressDialog progressDialog;

    private VersionManager versionInfo;

    public static UpdateVersionHelper versionHelper;

    public static UpdateVersionHelper getInstance() {
        if (versionHelper == null) {
            versionHelper = new UpdateVersionHelper();
        }
        return versionHelper;
    }

    public void start() {

        final String u = "version/mag/search/latest/one";
        Map<String, Object> pd = new HashMap<>();
        HttpUtils.getInstance().OkHttp3PostWithRequestBody(u, pd, new NetworkCallback() {
            @Override
            public void onSuccess(JSONObject obj) {
                try {
                    Object data = obj.get("data");
                    Gson gson = new Gson();
                    String appVersionName = CommonUtils.getAppVersionName(context);
                    versionInfo = gson.fromJson(data.toString(), VersionManager.class);
                    if (versionInfo != null && !appVersionName.equals(versionInfo.getVersionName())) {
                        newApkName = versionInfo.getVersionName() + ".apk";
                        downloadUrl = versionInfo.getDownloadUrl();
                        showUpdateDialog();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(String str) {
            }
        });

    }

    //显示更新提示按钮
    private void showUpdateDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("发现新版本，是否确定更新？").setIcon(android.R.drawable.ic_dialog_info)
                .setCancelable(false)
                .setNegativeButton("取消", null);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                createProgress();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        downloadApk();
                    }
                }).start();
            }
        });
        builder.show();

    }

    /**
     * 强制更新时显示在屏幕的进度条
     */
    private void createProgress() {
//        if (versionInfo)
        progressDialog = new ProgressDialog(context);
        progressDialog.setMax(100);
        progressDialog.setCancelable(false);
        progressDialog.setMessage("正在下载更新文件...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.show();

    }

    //下载更新包
    private void downloadApk() {
        try {
            final long startTime = System.currentTimeMillis();
            //获取文件名
            URL myURL = new URL(downloadUrl);
            URLConnection conn = myURL.openConnection();
            conn.connect();
            InputStream is = conn.getInputStream();
            int fileSize = conn.getContentLength();//根据响应获取文件大小
            if (fileSize <= 0) throw new RuntimeException("无法获知文件大小 ");
            if (is == null) throw new RuntimeException("stream is null");
            File file1 = new File(downLoadPath);
            if (!file1.exists()) {
                file1.mkdirs();
            }
            //把数据存入路径+文件名
            FileOutputStream fos = new FileOutputStream(downLoadPath + "/" + newApkName);
            byte buf[] = new byte[1024];
            int downLoadFileSize = 0;
            do {
                //循环读取
                int numread = is.read(buf);
                if (numread == -1) {
                    break;
                }
                fos.write(buf, 0, numread);
                downLoadFileSize += numread;
                progressDialog.setProgress((int) ((float) downLoadFileSize * 100 / fileSize));
                //更新进度条
            } while (true);
            delOldApk();
            progressDialog.dismiss();
            installApk();
            is.close();
        } catch (Exception ex) {
            progressDialog.dismiss();
            Log.e("DOWNLOAD", "error: " + ex.getMessage(), ex);
        }
    }

    //删除旧的安装包
    private void delOldApk() {
        File fileAPK = new File(downLoadPath, oldApkName);
        if (fileAPK.exists()) {
            fileAPK.delete();
        }
    }

    /**
     * 安装apk
     */
    private void installApk() {
        File file = new File(downLoadPath, newApkName);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        //判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".myprovider", file);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }
        context.startActivity(intent);
    }

    //设置上下文
    public UpdateVersionHelper setContext(Context context) {
        this.context = context;
        return this;
    }

    //设置下载apk地址
    public UpdateVersionHelper setUrl(String url) {
        this.downloadUrl = url;
        return this;
    }

    //设置新版本文件名
    public UpdateVersionHelper setNewFileName(String fileName) {
        this.newApkName = fileName;
        return this;
    }

    //设置旧版本文件名
    public UpdateVersionHelper setOldFileName(String fileName) {
        this.oldApkName = fileName;
        return this;
    }

    //设置下载路径
    public UpdateVersionHelper setDownloadPath(String downLoadPath) {
        this.downLoadPath = downLoadPath;
        return this;
    }
}
